package com.wildworld.coreimpl.services;


import com.wildworld.core.IMap;
import com.wildworld.core.events.IMapGeneratingEventListener;
import com.wildworld.core.events.IMapRedrawEventListener;
import com.wildworld.core.properties.MapProperty;
import com.wildworld.core.services.IMapService;
import com.wildworld.coreimpl.WildWorldMapImpl;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.stylesheets.LinkStyle;

import java.util.LinkedList;
import java.util.List;


/**
 * @author gzhebrakov
 *         Date: 20.07.12
 *         Time: 22:44
 */
@Service
public class WildWorldMapServiceImpl implements IMapService {

    private List<IMapGeneratingEventListener> generatingEventListenerList;

    public WildWorldMapServiceImpl(){

    }

    @Override
    public void addMapGeneratingEventListener(IMapGeneratingEventListener listener) {
        if (generatingEventListenerList == null){
            generatingEventListenerList = new LinkedList<IMapGeneratingEventListener>();
        }
        generatingEventListenerList.add(listener);
    }

    @Override
    public IMap generateMap() {
        WildWorldMapImpl map = new WildWorldMapImpl();
        emitGeneratingEvent(map);
        return map;
    }

    @Override
    public IMap generateMapByProperty(MapProperty property) {
        if (property != null){
           IMap map = new WildWorldMapImpl(property);
           emitGeneratingEvent(map);
           return map;
        }
        return generateMap();
    }

    private void emitGeneratingEvent(final IMap map){
        new Thread(new Runnable() {
            @Override
            public void run() {
                CollectionUtils.forAllDo(generatingEventListenerList, new Closure() {
                    @Override
                    public void execute(Object o) {
                        ((IMapGeneratingEventListener)o).mapGeneratedEvent(map);
                    }
                });
            }
        }).start();
    }
}
